package com.luozm.captcha;

import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 网络加载图片的Task类
 * Created by cdc4512 on 2018/5/7.
 */

class BitmapLoaderTask {

    private Callback callback;

    public BitmapLoaderTask(String url, Callback callback) {
        this.callback = callback;
        getImg(url);
    }

    private void getImg(String urlImage) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlImage);
            URLConnection urlConnection = url.openConnection();
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            }
            if (connection != null) {
                connection.connect();
                // 之后可进行url的其他操作
                // 得到服务器返回过来的流对象
                InputStream inputStream = urlConnection.getInputStream();
                ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
                ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                // 普通解码叠加旋转、缩放、裁剪
                PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
                callback.result(pixelMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    interface Callback {
        void result(PixelMap bitmap);
    }
}
